#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
using namespace std;

const std::string gpipefile = "./fifo";
const mode_t gfifomode = 0600;
const size_t gsize = 1024;
const int gdefault = -1;
const int gread = O_RDONLY;
const int gwrite = O_WRONLY;

class Fifo
{
private:
    void OpenFifo(int flag)
    {
        _fd = open(gpipefile.c_str(), flag);
        if (_fd < 0)
        {
            cout << "open pipefile error" << endl;
        }
    }
public:
    Fifo()
        : _fd(-1)
    {
        int n = mkfifo(gpipefile.c_str(), gfifomode);
        if (n < 0)
        {
            //cerr << "mkfifo error" << endl;
            return;
        }
        cout << "mkfifo success" << endl;
    }

    ~Fifo()
    {
        int n = unlink(gpipefile.c_str());
        if (n < 0)
        {
            cerr << "unlink error" << endl;
            return;
        }
        cout << "unlink success" << endl;
    }

    void OpenPipeForWrite()
    {
        OpenFifo(gwrite);
    }

    void OpenPipeForRead()
    {
        OpenFifo(gread);
    }

    int Wait()
    {
        int code = 0;
        ssize_t n = read(_fd, &code, sizeof(code));
        if (n == sizeof(code))
        {
            return 0;
        }
        else if (n == 0)
        {
            return 1;
        }
        else{
            return 2;
        }
    }

    void Signal()
    {
        int code = 1;
        ssize_t n = write(_fd, &code, sizeof(code));
    }

private:
    int _fd;
};

Fifo gpipe;